import { Injectable } from '@angular/core';
import { JPushService } from 'ionic2-jpush';
import { Platform, Events } from 'ionic-angular';
// import {LogUtils} from "../log-utils";


@Injectable()
export class JpushService {
    //   jPushPlugin;

    constructor(public jPushPlugin: JPushService,
        public platform: Platform,
        public events: Events) {

    }

    openListenEvent() {
        document.removeEventListener("jpush.receiveNotification", function () { });
        document.removeEventListener("jpush.openNotification", function () { });
        document.removeEventListener("jpush.receiveMessage", function () { });
        document.removeEventListener("jpush.setTagsWithAlias", function () { });

        document.addEventListener("jpush.receiveNotification", this.onReceiveNotification, false);
        document.addEventListener("jpush.openNotification", this.onOpenNotification, false);
        document.addEventListener("jpush.receiveMessage", this.onReceiveMessage, false);
        document.addEventListener("jpush.setTagsWithAlias", this.onTagsWithAlias, false);
    }

    init() {
        return this.jPushPlugin.init();
    }


    getRegistrationID() {
        return this.jPushPlugin.getRegistrationID();
    }

    stop() {
        try {
            this.jPushPlugin.stopPush();
        } catch (execption) {
            console.log(execption);
        }
    }

    setBadge(number){
        if (this.platform.is('ios')) {
            this.jPushPlugin.setApplicationIconBadgeNumber(number)
            .then(res => console.log(res))
            .catch(err => console.log(err))
        }
    }

   

    //接收新的推送通知
    onReceiveNotification = (event)=> {

        try {
            // var alertContent
            // if (this.platform.is("ios")) {
            //     alertContent = event.aps.alert;
            // } else if (this.platform.is("android")) {
            //     alertContent = event.alert;
            // };
            // alert(alertContent);
            console.log("onReceiveNotification");
        } catch (execption) {
            console.log(execption);
        }
    }

    //打开通知消息
    onOpenNotification= (event)=> {
        // alert("打开了通知1");
        var that = this;
        that.platform.ready().then(() => {
            that.events.publish('GET_MESSAGE');    
        })
        
        try {
            console.log("onOpenNotification");
        } catch (execption) {
            console.log(execption);
        }
    }

    //收到自定义消息后的回调
    onReceiveMessage = (event)=> {
        try {
            console.log("onReceiveMessage");
        } catch (execption) {
            console.log(execption);
        }
    }

    //返回设置标签和别名结果
    onTagsWithAlias = (event)=> {
        try {
            console.log("onTagsWithAlias");
        } catch (execption) {
            console.log(execption);
        }
    }

 
}
